package cs6238.common.message;

import cs6238.common.ByteArray;
import cs6238.common.message.command.Command;
import cs6238.common.message.command.DelegateCommand;
import cs6238.common.message.command.GetFileCommand;
import cs6238.common.message.command.ListHostsCommand;
import cs6238.common.message.command.LsCommand;
import cs6238.common.message.command.PutFileCommand;
import cs6238.common.message.response.ListHostsResponse;
import cs6238.common.message.response.LsResponse;
import cs6238.common.message.response.Response;
import cs6238.common.message.response.StandardResponse;

/**
 * Used for deserializing commands
 */
public class MessageFactory {
	
	
	public static Command createCommand(byte[] buffer){
		MessageId commandId = MessageId.values()[ByteArray.readInt(buffer)];
		
		Command command = null;
		switch(commandId){
			case LS_COMMAND:
				command = new LsCommand();
				break;
			case LIST_HOSTS_COMMAND:
				command = new ListHostsCommand();
				break;
			case GET_FILE_COMMAND:
				command = new GetFileCommand();
				break;
			case PUT_FILE_COMMAND:
				command =  new PutFileCommand();
				break;
			case DELEGATE_COMMAND:
				command = new DelegateCommand();
				break;
		}
		
		if(command != null){
			command.deserialize(buffer);
		}
		
		return command;
	}
	
	public static Response createResponse(byte[] buffer){
		MessageId responseId = MessageId.values()[ByteArray.readInt(buffer)];
		
		Response response = null;
		switch(responseId){
			case LS_RESPONSE:
				response = new LsResponse();
				break;
			case STANDARD_RESPONSE:
				response = new StandardResponse();
				break;
			case LIST_HOSTS_RESPONSE:
				response = new ListHostsResponse();
				break;
		}
		
		if(response != null){
			response.deserialize(buffer);
		}
		
		return response;
	}

}
